

// import QN from './qn1.js'
import QN from './QN.js'
// const QN = require('./QN.js').default
//<script sr="QN.js"></script>

console.log('QN', QN)

let currentDevice = null//用于存储当前设备

let ble = {
  discovery() {
    //开始扫描周围的设备
    wx.startBluetoothDevicesDiscovery({
      success: res => {
        console.log('开启扫描成功')
      },
      fail: err => {
        console.log('开启扫描失败')
      }
    })
  },
  stopDiscovery() {
    //扫到设备后，停止扫描
    wx.stopBluetoothDevicesDiscovery({
      success: res => {
        console.log('停止扫描成功')
      },
      fail: err => {
        console.log('停止扫描失败')
      }
    })
  }
}


Page({

  /**
   * 页面的初始数据
   */
  data: {
    weight: 0,
    available: false,
    discovering: false,
    connected: false
  },

  /**
   * 生命周期函数--监听页面加载
   */
  close() {
    let { connected } = this.data

    if (connected) {
      wx.closeBLEConnection({
        deviceId: currentDevice.deviceId,
        success: res => {
          currentDevice = null
          console.log('断开连接成功')
        },
        fail: err => {
          console.log('断开连接失败')
        }
      })
    }
  },
  discovery() {
    ble.discovery()
  },
  restart() {
    let { connected } = this.data
    if (connected) {
      wx.closeBLEConnection({
        deviceId: currentDevice.deviceId,
        success: res => {
          currentDevice = null
          console.log('断开连接成功')
          ble.discovery()
        },
        fail: err => {
          console.log('断开连接失败')
        }
      })
    } else {
      currentDevice = null
      ble.discovery()
    }
  },
  onLoad: function (options) {
    
    //打开蓝牙模块
    wx.openBluetoothAdapter({
      success: res => {
        console.log('打开蓝牙模块成功')
        //开始扫描设备
        ble.discovery()
      },
      fail: err => {
        console.log('打开蓝牙模块失败')
      }
    })

    //监听蓝牙开关、是否有开启扫描设备
    wx.onBluetoothAdapterStateChange(res => {
      let { available, discovering } = res

      this.setData({
        available
      })

      if (available) {
        console.log('蓝牙已打开')
      } else {
        //清掉
        currentDevice = null
        console.log('蓝牙已关闭')
      }
    })

    //监听设备连接状态
    wx.onBLEConnectionStateChange(res => {
      let { deviceId, connected } = res

      this.setData({
        connected
      })
      if (connected) {
        console.log('连接成功')
      } else {
        console.log('连接已经断开')
      }

    })

    // ArrayBuffer转16进制字符串示例
    function ab2hex(buffer) {
      let hexArr = Array.prototype.map.call(
        new Uint8Array(buffer),
        function (bit) {
          return ('00' + bit.toString(16)).slice(-2)
        }
      )
      return hexArr.join('')
    }

    //监听低功耗蓝牙设备的特征值变化事件
    wx.onBLECharacteristicValueChange(({ deviceId, value }) => {
      //转成16进制字符
      value = ab2hex(value)

      //根据特征值变化，获取对应的返回结果
      let result = QN.cmd({
        device: currentDevice, 
        value
      })
      
      if (result) {
        let { code, weight, encryptStr } = result

        if (code == 3001) {//测量中
          this.setData({
            weight
          })
        } else if (code == 3002) {
          //心率秤首次返回的命令
          //通过encryptStr，算出对应的指标
          //再通过 QN.itemCmdString 获取对应的体脂、bmi命令，然后发布给体脂秤显示
          result.cmdString = QN.itemCmdString({
            gender: 1,//性别
            bodyfat: 19.2,//体脂率，类型值为3
            bmi: 20//bmi，类型值2
          })
          
        }

        if (result.cmdString) {//向蓝牙秤发送命令

          if (code == 3003) {
            //拿到对应的encryptStr加密字符
            console.log('测量完成', encryptStr)
            wx.request({
              method: 'post',
              url: 'http://192.168.2.65:5566/1',
              data: {
                hexString: encryptStr
              },
              success: res => {
                console.log('res2', res)
              }
            })
          }
          const ab = new ArrayBuffer(result.cmdString.length)
          const dv = new DataView(ab)

          result.cmdString.forEach((value, index) => {
            dv.setUint8(index, value)
          })

          wx.writeBLECharacteristicValue({
            deviceId,
            serviceId: result.serviceId,
            characteristicId: result.writeCharacteristicId,
            value: ab,
            success: () => {
              console.log('发送成功')
            }
          })
        }
      }

    })

    //监听寻找到新设备的事件
    wx.onBluetoothDeviceFound(devices => {
      let { localName, RSSI, advertisData, deviceId } = devices.devices[0]

      let deviceObj = {
        deviceId,
        localName,
        RSSI,
        advertisData: ab2hex(advertisData)//转成16进制字符
      }
      let device = QN.getDevice(deviceObj)//获取蓝牙设备

      if (device) {
        
        //如果是广播秤
        if (device.isBroadcast) {
          if (currentDevice && device.mac != currentDevice.mac) return
          
          currentDevice = device
          onBroadcastScale(device)//广播秤处理逻辑
        } else {//蓝牙秤
          currentDevice = device
          //扫到设备后停止扫描
          ble.stopDiscovery()

          createConnect()//蓝牙秤处理逻辑
        }
      }

    })

    let that = this
    //广播秤的处理
    function onBroadcastScale(device) {
      let { code, encryptStr, weight } = device
      
      if (code == 3001) {//测量中
        that.setData({
          weight
        })
      } else if (code == 3003) {//测量完成,得到encryptStr加密字符,并停止扫描
        console.log('测量完成', encryptStr)
        //测量完成，停止扫描，使广播秤不再接收数据
        ble.stopDiscovery()
      }
    }

    //与currentDevice蓝牙设备的连接
    function createConnect() {
      let { deviceId } = currentDevice

      //连接扫描到的设备
      wx.createBLEConnection({
        deviceId,
        success: res => {

          //获取设备特征值
          wx.getBLEDeviceServices({
            deviceId,
            success: res => {
              console.log('getBLEDeviceServices res', res)
              //存储当前设备的服务
              let currentServices = QN.getServices(res.services)
              console.log('currentServices', currentServices)
              //获取蓝牙设备某个服务中所有特征值
              wx.getBLEDeviceCharacteristics({
                deviceId,
                serviceId: currentServices.serviceId,
                success: res => {

                  //启用低功耗蓝牙设备特征值变化时的 notify 功能
                  wx.notifyBLECharacteristicValueChange({
                    state: true, // 启用 notify 功能
                    // 这里的 deviceId 需要已经通过 createBLEConnection 与对应设备建立链接
                    deviceId,
                    // 这里的 serviceId 需要在 getBLEDeviceServices 接口中获取
                    serviceId: currentServices.serviceId,
                    // 这里的 characteristicId 需要在 getBLEDeviceCharacteristics 接口中获取
                    characteristicId: currentServices.readCharacteristicId,
                    success: res => {
                      console.log('创建连接成功完成')
                      
                    },
                    fail: err => {
                      console.log('创建连接成功失败')
                    }
                  })
                },
                fail: err => {
                  console.log('获取特征值失败 err', err)
                }
              })

            },
            fail: err => {
              console.log('获取服务失败 err', err)
            }
          })

        },
        fail: err => {
          console.log('蓝牙连接失败')
        }
      })
  
      
    }
  }
})